# -*- coding: utf-8 -*-
# @Time    : 2021/11/2 15:31
# @Author  : huangwei
# @File    : draw_method.py
# @Software: PyCharm
import numpy as np
import cv2
from skimage import measure


def sort_box( box ):
    """
    将四个点按左上、右上、右下、左下排序输出
    :param box:
    :return:
    """
    x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]
    pts = (x1, y1), (x2, y2), (x3, y3), (x4, y4)
    pts = np.array(pts, dtype="float32")

    # 先按 x 坐标大小进行排序，即从左到右进行排序
    x_sorted = pts[np.argsort(pts[:, 0]), :]
    # 对最左边两个点进行上下排序，分出左上角和左下角
    left_points = x_sorted[:2, :]
    right_points = x_sorted[2:, :]

    left_sort = left_points[np.argsort(left_points[:, 1]), :]
    left_top, left_down = left_sort

    # 同理可分出右上和右下
    right_sort = right_points[np.argsort(right_points[:, 1]), :]
    right_top, right_down = right_sort

    (x1, y1), (x2, y2), (x3, y3), (x4, y4) = np.array([left_top, right_top, right_down, left_down], dtype="float32")

    # return x1 - 1, y1 - 1, x2 + 1, y2 - 1, x3 + 1, y3 + 1, x4 - 1, y4 + 1
    return x1, y1, x2, y2, x3, y3, x4, y4


def minAreaRectBox( coords ):
    """ 连通区域的外接矩形 """
    rect = cv2.minAreaRect(coords[:, ::-1])
    box = cv2.boxPoints(rect)
    box = box.reshape((8,)).tolist()
    box = sort_box(box)
    return box


def draw_lines( img, lines, color=(0, 0, 0), line_width=3 ):
    """
    图片上画线
    :param img:
    :param lines:
    :param color:
    :param line_width:
    :return:
    """
    tmp = np.copy(img)
    for line in lines:
        x1, y1, x2, y2 = line
        cv2.line(tmp, (int(x1), int(y1)), (int(x2), int(y2)), color, line_width, lineType=cv2.LINE_AA)

    return tmp


def draw_box( img, box ):
    x1, y1, x2, y2, x3, y3, x4, y4 = box
    p1 = (int(x1), int(y1))
    p2 = (int(x2), int(y2))
    p3 = (int(x3), int(y3))
    p4 = (int(x4), int(y4))

    cv2.line(img, p1, p2, (0, 255, 0), 1)
    cv2.line(img, p2, p3, (0, 255, 0), 1)
    cv2.line(img, p3, p4, (0, 255, 0), 1)
    cv2.line(img, p4, p1, (0, 255, 0), 1)

    return img


def draw_img( input_size, lines, output_path, color=255, line_width=1 ):
    """
    将线画在黑板上
    :param line_width:
    :param color:
    :param input_size:
    :param lines:
    :param output_path:
    :return:
    """
    # 将提取出的线画在黑板上
    tmp = np.zeros(input_size, dtype='uint8')
    tmp = draw_lines(tmp, lines, color=color, line_width=line_width)
    cv2.imwrite(output_path, tmp)


def draw_table( img, lines, output_path ):
    h, w = img.shape[:2]
    tmp = np.zeros((h, w), dtype='uint8')
    tmp = draw_lines(tmp, lines, color=255, line_width=1)

    table_labels = measure.label(tmp == 0, connectivity=2)
    regions = measure.regionprops(table_labels)
    rboxes = []
    for region in regions:
        if region.bbox_area < img.shape[0] * img.shape[1] / 2:
            rbox = minAreaRectBox(region.coords)
            rboxes.append(rbox)

    print("表格框数量为：", len(rboxes))
    table_box_img = np.copy(img)
    for box in rboxes:
        draw_box(table_box_img, box)
    cv2.imwrite(output_path, table_box_img)

    return rboxes


def draw_text_boxes( img, boxes, save_path ):
    """
    画找出来的文本框
    :param img:
    :param boxes:
    :param save_path:
    :return:
    """
    img_back = np.copy(img)
    for box in boxes:
        x1, y1 = box[0]
        x2, y2 = box[1]
        x3, y3 = box[2]
        x4, y4 = box[3]

        p1 = (int(x1), int(y1))
        p2 = (int(x2), int(y2))
        p3 = (int(x3), int(y3))
        p4 = (int(x4), int(y4))

        cv2.line(img_back, p1, p2, (0, 255, 0), 1)
        cv2.line(img_back, p2, p3, (0, 255, 0), 1)
        cv2.line(img_back, p3, p4, (0, 255, 0), 1)
        cv2.line(img_back, p4, p1, (0, 255, 0), 1)

    cv2.imwrite(save_path, img_back)
